<template>
	<view class="free-content">
		<view class="free-tabs">
			<view  :class="{'tab-active' : item.id == current}" v-for="item in tabList" :key="item.id" @click="changeTab(item.id)">{{item.name}}</view>
		</view>
		<scroll-view scroll-y="true" :style="'height:'+freeHeight+'px'" @scrolltolower="loadMore">
			<view class="free-list">
					<course-card :list="courseList.value"></course-card>
			</view>
		</scroll-view>
	</view>
</template>


<script setup>
import {ref, reactive,toRaw,defineExpose,defineProps,nextTick,onMounted} from 'vue'
import courseCard from '../common/card.vue'
import { searchCourse } from '../../api/home.js'
const props = defineProps({
	swiperHeight: Number
})
const freeHeight = ref(0)
const tabList = [
	{id: 0,name: '综合推荐'},
	{id: 1,name: '最新'},
	{id: 2,name: '浏览最多'}
]
const current = ref(0)
const courseList = reactive([])
const pageNum = ref(1)
const isFinish = ref(false)
const getList = ()=>{
	let pageSize = 10
	let sortBy = current.value === 0 ? '' : (current.value === 1 ? 'time-desc' : 'clicks-asc')
	let params = {
		pageNum: pageNum.value,
		pageSize,
		entity: {
			isFree: 1,
			sortBy
		}
	}
	searchCourse(params).then(res=>{
		let list = res.data.pageInfo.list
		if (list.length) {
			courseList.value = toRaw(courseList.value) ? [...toRaw(courseList.value),...list]  : list
		}
		if (list.length < pageSize) {
			isFinish.value = true
		}
	})
}
const changeTab = (id) => {
	current.value = id
}
const initList = ()=> {
	pageNum.value = 1
	courseList.value = []
	isFinish.value = false
	current.value = 0
	getList()
}
const loadMore = ()=>{
	if (isFinish.value) return
	pageNum.value++
	getList()
}
defineExpose({
	initList
})
onMounted(()=>{
	nextTick(()=>{
		let tabs = uni.createSelectorQuery().select('.free-tabs')
		tabs.boundingClientRect((res)=>{
			freeHeight.value = props.swiperHeight - res.height
		}).exec()
	})
})
</script>

<style lang="scss">
.free-tabs{
	display: flex;
	margin: 20rpx;
	font-size:25rpx;
	>view{
		margin-right: 30rpx;
		color: #d4d4d4;
	}
	.tab-active{
		color: #000000;
		font-weight: 700;
	}
}
.free-list{
	margin: 0 20rpx;
	padding-bottom: 50rpx;
}
</style>